package io.mya.common.utils;

import org.apache.commons.lang.StringUtils;

import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 特殊工具使用类
 * @author  PGmm
 * @date 2017-10-29
 */
public class SpecialUtil {

    /**
     *
     * 方法用途: 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序），并且生成url参数串<br>
     * 实现步骤: <br>
     *
     * @param paraMap   要排序的Map对象
     * @param urlEncode   是否需要URLENCODE
     * @param keyToLower    是否需要将Key转换为全小写
     *            true:key转化成小写，false:不转化
     * @return
     */
    public static String formatUrlMap(Map<String, String> paraMap, boolean urlEncode, boolean keyToLower)
    {
        String buff = "";
        Map<String, String> tmpMap = paraMap;
        try
        {
            List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(tmpMap.entrySet());
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
            Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>()
            {

                @Override
                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2)
                {
                    return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            });
            // 构造URL 键值对的格式
            StringBuilder buf = new StringBuilder();
            for (Map.Entry<String, String> item : infoIds)
            {
                if (StringUtils.isNotBlank(item.getKey()))
                {
                    String key = item.getKey();
                    String val = item.getValue();
                    if (urlEncode)
                    {
                        val = URLEncoder.encode(val, "utf-8");
                    }
                    if (keyToLower)
                    {
                        buf.append(key.toLowerCase() + "=" + val);
                    } else
                    {
                        buf.append(key + "=" + val);
                    }
                    buf.append("&");
                }

            }
            buff = buf.toString();
            if (buff.isEmpty() == false)
            {
                buff = buff.substring(0, buff.length() - 1);
            }
        } catch (Exception e)
        {
            return null;
        }
        return buff;


    }
    public static String toHex(byte[] buf) {
        StringBuffer strbuf = new StringBuffer(buf.length * 2);

        for(int i = 0; i < buf.length; ++i) {
            if ((buf[i] & 255) < 16) {
                strbuf.append("0");
            }

            strbuf.append(Long.toString((long)(buf[i] & 255), 16));
        }

        return strbuf.toString();
    }

    public static String toMD5(String str) {
        if (str == null) {
            return null;
        } else {
            MessageDigest md = null;

            try {
                md = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException var3) {
                var3.printStackTrace();
                return null;
            }

            md.update(str.getBytes());
            byte[] tmp = md.digest();
            return toHex(tmp);
        }
    }

    public static String genCaiMi(){
        synchronized(GenNumbersUtil.class){
            String code = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 12);
            code = code+ getRandomStr(8);
            //System.out.println(code.toUpperCase());
            //System.out.println(code.length());
            return code.toUpperCase();
        }

    }

    public static boolean isEmpty(Object obj) {
        if (obj instanceof String) {
            return obj == null || "".equals((String)obj);
        } else if (obj instanceof Object[]) {
            return obj == null || ((Object[])((Object[])obj)).length == 0;
        } else if (obj instanceof Collection) {
            return obj == null || ((Collection)obj).size() == 0;
        } else {
            return obj == null;
        }
    }

    public static boolean isNotEmpty(Object obj) {
        return !isEmpty(obj);
    }
    public static String getRandomStr(int count) {
        StringBuffer sb = new StringBuffer();
        String str = "0123456789abcdefjhijklmnopqrstuvwxyz";
        Random r = new Random();

        for(int i = 0; i < count; ++i) {
            int num = r.nextInt(str.length());
            sb.append(str.charAt(num));
            str = str.replace(str.charAt(num) + "", "");
        }

        return sb.toString();
    }
    public static String getRandomNum(int count) {
        StringBuffer sb = new StringBuffer();
        String str = "0123456789";
        Random r = new Random();

        for(int i = 0; i < count; ++i) {
            int num = r.nextInt(str.length());
            sb.append(str.charAt(num));
            str = str.replace(str.charAt(num) + "", "");
        }

        return sb.toString();
    }
}
